<template>
	<view>
		<uni-popup ref="popup" type="bottom">
			<view class="bg-white ">
				<uni-section title="添加客户信息" type="circle">
					<template v-slot:right>
						<view @click="close">关闭</view>
					</template>
				</uni-section>
				<view class="padding-bottom-lg padding-sm" style="padding-bottom: 120rpx;">
					<uni-forms class="margin-sm" labelWidth="160rpx" ref="submitForm" :modelValue="from" :rules="rules">

						<view style="display: flex;">
							<view style="flex: 1;">
								<uni-forms-item label="学生姓名" required name="name">
									<uni-easyinput v-model="from.name"></uni-easyinput>
								</uni-forms-item>
								<uni-forms-item label="手机号" required name="phone">
									<uni-easyinput type="number" v-model="from.phone"></uni-easyinput>
								</uni-forms-item>
							</view>
							<view style="width: 200rpx;" class="juzhong">
								<view class="margin-bottom-lg margin-left-lg"
									@click="updateStudentImg(getimg(from.student))">
									<image :src="getimg(from.student)" style="width: 150rpx;height: 150rpx;"></image>
								</view>
							</view>
						</view>
						<uni-forms-item label="出生日期">
							<view style="display: flex;">
								<view style="width: 350rpx;"><uni-datetime-picker type="date"
										v-model="from.dateOfBirth" /></view>
								<view class="juzhong bg-olive radius margin-left-lg" style="flex: 1;">
									{{dateToAge(from.dateOfBirth)}}
								</view>
							</view>
						</uni-forms-item>

						<uni-forms-item label="顾问" required name="principalTeacher">
							<uni-data-select @change="asdfasdf" v-model="from.courseConsultantId"
								:localdata="dict.createUserNameList" placeholder="选择顾问"></uni-data-select>
						</uni-forms-item>


						<uni-forms-item label="性别" required name="sex">
							<uni-data-checkbox style="width: 100%;" mode="button" v-model="from.sex"
								:localdata="sexList"></uni-data-checkbox>
						</uni-forms-item>

						<uni-forms-item label="来源" required name="sourceId">
							<uni-data-picker :localdata="sourceList" :map="{text:'label',value:'value'}"
								v-model="from.sourceId" popup-title="请选择来源" @change="onchange"
								@nodeclick="onnodeclick"></uni-data-picker>
						</uni-forms-item>


						<uni-forms-item label="星级">
							<uni-rate v-model="from.level" />
						</uni-forms-item>

						<uni-forms-item label="备注">
							<uni-easyinput v-model="from.remark"></uni-easyinput>
						</uni-forms-item>
					</uni-forms>
					<button @click="submitForm" class="login-btn cu-btn block bg-blue lg round">提交</button>
				</view>
			</view>
		</uni-popup>
		<updateAvatar ref="updateAvatar" @imgOk="uploadOk"></updateAvatar>
	</view>
</template>

<script>
	import updateAvatar from "@/pages/mine/avatar/index"
	import {
		doInsert
	} from '@/api/marketing/communication'

	import {
		doInsert as doInsertCustomer,
		doUpdate
	} from "@/api/marketing/customer/CustomerManagementApi";

	import {
		formatTime,
		dateToAge,
		isNull,
		isJson
	} from '@/utils/validate'
	import {
		getcommon,
		pictureProcessing,
	} from '@/utils/common'
	export default {
		components: {
			updateAvatar
		},
		data() {
			return {
				dict: {

				},
				datetimesingle: new Date(),
				from: {
					student: null,
					sex: null,
					dateOfBirth: null,
					imageUrl: null,
					name: null,
					parentsInfo: null,
					phone: null,
					level: 0,
					sourceId: null,
					remark: null,
				},
				sourceList: [],
				sexList: [{
						text: '男孩',
						value: "1"
					},
					{
						text: '女孩',
						value: "0"
					}
				],
				// 校验规则
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '姓名不能为空'
						}]
					},
					sex: {
						rules: [{
							required: true,
							errorMessage: '性别必选'
						}, {
							format: 'number',
							errorMessage: '年龄只能输入数字'
						}]
					},
					phone: {
						rules: [{
							required: true,
							errorMessage: '手机号不能为空'
						}, {
							format: 'number',
							errorMessage: '手机号只能输入数字'
						}]
					},
					sourceId: {
						rules: [{
							required: true,
							errorMessage: '来源不能为空'
						}]
					}

				},
			}

		},
		props: {
			customerId: null,

			customer: {}
		},
		mounted() {
			this.sourceList = getcommon("sourceList")
			console.log(this.sourceList);
		},
		methods: {
			asdfasdf(e) {
				console.log(e);
				console.log(this.from.sourceId);
			},
			uploadOk(e) {

				this.from.imageUrl = e
			},
			getimg(data) {
				return pictureProcessing(data)
			},
			dateToAge(date) {
				return dateToAge(date)
			},
			open(data) {
				Object.assign(this.from, this.$options.data().from);
				this.dict.createUserNameList = getcommon("createUserNameList");

				for (let s of this.dict.createUserNameList) {

					s.text = s.realName
					s.value = s.id
				}

				if (!isNull(data)) {
					this.from = Object.assign({}, data);
					this.from.sex = data.student.sex
					this.from.dateOfBirth = data.student.dateOfBirth
					this.from.imageUrl = data.student.imageUrl
					this.from.name = data.student.name
					this.from.phone = data.parentsInfo.phone
					this.from.sourceId = JSON.parse(data.sourceId)
					this.from.sourceId = this.from.sourceId.pop();
					console.log(this.from.sourceId);
				} else {
					this.from.parentsInfo = {}
					this.from.student = {}
				}

				this.$refs.popup.open()
			},
			findParentId(arr, targetId) {
				for (const parent of arr) {
					for (const child of parent.children) {
						if (child.value === targetId) {
							return parent.value; // 返回父级 ID
						}
					}
				}
				return null; // 如果未找到，返回 null
			},
			async submitForm() {
				console.log(this.from.sourceId);
				this.$refs['submitForm'].validate().then(async res => {
					let asdf = Object.assign({}, this.from);
					console.log(1);
					asdf.student.sex = this.from.sex
					asdf.student.dateOfBirth = this.from.dateOfBirth
					asdf.student.imageUrl = this.from.imageUrl
					asdf.student.name = this.from.name
					asdf.parentsInfo.phone = this.from.phone


					if (!isJson(asdf.sourceId)) {
						let sourceId = this.findParentId(this.sourceList, asdf.sourceId)
						console.log(sourceId);
						let p = []
						p.push(sourceId)
						p.push(asdf.sourceId)
						asdf.sourceId = JSON.stringify(p)
					}
					console.log(asdf.sourceId);
					console.log(1);
					if (!isNull(asdf.id)) {
						const {
							success,
							msg
						} = await doUpdate(asdf);
						if (success) {

						}
					} else {
						let {
							success
						} = await doInsertCustomer(asdf)
					}




				})

			},
			onchange(e) {
				console.log(e.detail.value);
				let value = e.detail.value
				let arrayOfIDs = value.map(obj => obj.value);
				this.from.sourceId = JSON.stringify(arrayOfIDs)
			},
			onnodeclick(node) {},
			close() {
				Object.assign(this.$data, this.$options.data());
				this.$refs.popup.close()
				// uni.showTabBar();
				this.$emit('refresh')
			},
			/**
			 * 修改客户头像
			 * @param {Object} id
			 */
			updateStudentImg(img) {
				this.$refs.updateAvatar.open(img)
				// this.$tab.navigateTo('/pages/mine/avatar/index?id=' + id + "&img=" + img)
			},
			/**
			 * 修改客户头像
			 * @param {Object} id
			 */
			updateStudentImg(id, img) {
				this.$tab.navigateTo('/pages/mine/avatar/index?id=' + id + "&img=" + img)
			}
		}
	}
</script>

<style>
</style>